package com.bndg.bndggame;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.bndg.bndggame.bean.RankBean;
import com.bndg.bndggame.httprequest.GetRequest_InterFace;
import com.bndg.bndggame.httprequest.PostRequest_Interface;
import com.bndg.bndggame.httprequest.RetrofitManager;
import com.bndg.bndggame.tools.BitmapUtils;
import com.bndg.bndggame.tools.ScreenUtils;
import com.bndg.bndggame.view.MyViewGroup;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, MyViewGroup.OverListener {

    private int[] ints = {200, -200, 200, -200};
    private int count = -1;
    private MyViewGroup myViewGroup;
    private Chronometer timer;
    private ImageView iv;
    private final int TAKE_PHOTO = 1;
    private File outputImagepath;
    private final int SELECT_PHOTO = 2;
    private View ll_contain;
    private ProgressBar loading;
    private Bitmap fitBitmap;
    private View randomLayout;
    private int gameTag = 3;
    private ArrayList<RankBean.RanklistBean> ranklistBeans = new ArrayList<>();
    private String mToken;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        randomLayout = findViewById(R.id.tv_start);
        iv = findViewById(R.id.iv);
        loading = findViewById(R.id.loading);
        ll_contain = findViewById(R.id.ll_contain);
        randomLayout.setOnClickListener(this);
        myViewGroup = findViewById(R.id.view_background);
        myViewGroup.setOverListener(this);
        timer = (Chronometer) findViewById(R.id.timer);
        myViewGroup.setTimer(timer);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestImei();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_three:
                if (myViewGroup != null) {
                    gameTag = 3;
                    myViewGroup.setSquareCount(3);
                    myViewGroup.removeAllViews();
                    myViewGroup.init();
                }
                break;
            case R.id.menu_four:
                gameTag = 4;
                if (myViewGroup != null) {
                    myViewGroup.setSquareCount(4);
                    myViewGroup.removeAllViews();
                    myViewGroup.init();
                }
                break;
            case R.id.menu_five:
                gameTag = 5;
                if (myViewGroup != null) {
                    myViewGroup.setSquareCount(5);
                    myViewGroup.removeAllViews();
                    myViewGroup.init();
                }
                break;
            case R.id.custom_background:
                if (myViewGroup != null) {
                    select_photo();
                }
                break;
            case R.id.ranklist_background:
                Intent intent = new Intent(this, RankListActivity.class);
                startActivity(intent);
                break;
            case R.id.number_background:
                if (myViewGroup != null) {
                    iv.setVisibility(View.GONE);
                    myViewGroup.setBitmap(null);
                    myViewGroup.removeAllViews();
                    myViewGroup.init();
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(final View view) {

        switch (view.getId()) {
            case R.id.tv_start:

                if (myViewGroup != null) {
                    myViewGroup.randomLayout();
                }
                break;
        }
    }

    /**
     * 打开相机
     */
    public void openCamera() {
        //checkSelfPermission 检测有没有 权限
//        PackageManager.PERMISSION_GRANTED 有权限
//        PackageManager.PERMISSION_DENIED  拒绝权限
        //一定要先判断权限,再打开相机,否则会报错
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //权限发生了改变 true  //  false,没有权限时
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                new AlertDialog.Builder(this).setTitle("title")
                        .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 请求授权
                                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                            }
                        }).setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //不请求权限的操作
                    }
                }).create().show();
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
            }
        } else {
            take_photo();//已经授权了就调用打开相机的方法
        }
    }

    /**
     * 拍照获取图片
     **/
    public void take_photo() {
        //获取系統版本
        int currentapiVersion = Build.VERSION.SDK_INT;
        // 激活相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断存储卡是否可以用，可用进行存储
        if (hasSdcard()) {
            SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                    "yyyy_MM_dd_HH_mm_ss");
            String filename = timeStampFormat.format(new Date());
            outputImagepath = new File(Environment.getExternalStorageDirectory(),
                    filename + ".jpg");
            if (currentapiVersion < 24) {
                // 从文件中创建uri
                Uri uri = Uri.fromFile(outputImagepath);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            } else {
                //兼容android7.0 使用共享文件的形式
                ContentValues contentValues = new ContentValues(1);
                contentValues.put(MediaStore.Images.Media.DATA, outputImagepath.getAbsolutePath());
                Uri uri = getApplication().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            }
        }
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
        startActivityForResult(intent, TAKE_PHOTO);
    }


    /*
     * 判断sdcard是否被挂载
     */
    public static boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    /**
     * 从相册中获取图片
     */
    public void select_photo() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            openAlbum();
        }
    }

    /**
     * 打开相册的方法
     */
    private void openAlbum() {
        Log.d(">>>>", "-=-=--=-=-=-=-=-=打开相册11" + System.currentTimeMillis());
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, SELECT_PHOTO);
    }


    /**
     * 4.4以下系统处理图片的方法
     */
    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    /**
     * 4.4及以上系统处理图片的方法
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    private void handleImgeOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        Log.d(">>>>", "-=-=--=-=-=-=-=-=打开相册2222=======" + System.currentTimeMillis());
        Log.d("uri=intent.getData :", "" + uri);
        if (DocumentsContract.isDocumentUri(this, uri)) {
            String docId = DocumentsContract.getDocumentId(uri);        //数据表里指定的行
            Log.d("getDocumentId(uri) :", "" + docId);
            Log.d("uri.getAuthority() :", "" + uri.getAuthority());
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }

        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            imagePath = getImagePath(uri, null);
        }
        displayImage(imagePath);
    }

    /**
     * 通过uri和selection来获取真实的图片路径,从相册获取图片时要用
     */
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }


    /**
     * 拍完照和从相册获取玩图片都要执行的方法(根据图片路径显示图片)
     */
    private void displayImage(String imagePath) {
        if (!TextUtils.isEmpty(imagePath)) {
            setMyViewGroupBitmap(imagePath);
//            orc_bitmap = comp(BitmapFactory.decodeFile(imagePath)); //压缩图片
//            ImgUpdateDirection(imagePath);//显示图片,并且判断图片显示的方向,如果不正就放正
        } else {
            Toast.makeText(this, "图片获取失败", Toast.LENGTH_LONG).show();
        }
    }

    private void setMyViewGroupBitmap(final String imagePath) {
//        Bitmap bitmap = BitmapUtils.ReadBitmapById(this, R.drawable.back);
        startProgressBar();
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                getBitmap(imagePath);
//            }
//        }, 350);

        new Thread() {
            @Override
            public void run() {
                getBitmap(imagePath);
            }
        }.start();
    }

    private void getBitmap(String imagePath) {
        int degree = BitmapUtils.readPictureDegree(imagePath);
        Log.d(">>>>", "-=-=--=-=-=-=-=-=打开相册33=====" + System.currentTimeMillis());
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);//获取图片
        Log.d(">>>>", "-=-=--=-=-=-=-=-=打开相册44=====" + System.currentTimeMillis());
        /**
         * 把图片旋转为正的方向
         */
        Bitmap newbitmap = BitmapUtils.rotaingImageView(degree, bitmap);
        Bitmap compressImage = BitmapUtils.getImage(newbitmap);
        Log.d(">>>>", "-=-=--=-=-=-=-=-=打开相册55=====" + System.currentTimeMillis());
        int newWidth = ScreenUtils.getScreenWidth(MyApp.mContext) - 60;
        int maxHeight = ScreenUtils.getScreenHeight(MyApp.mContext) - ll_contain.getHeight() - 75;
        fitBitmap = BitmapUtils.fitBitmap(compressImage, newWidth, maxHeight);
        Log.d(">>>>", "-=-=--=-=-=-=-=-=打开相册66=====" + System.currentTimeMillis());
        callMainThread();
    }

    private void callMainThread() {
        myViewGroup.post(new Runnable() {
            @Override
            public void run() {
                myViewGroup.setBitmap(fitBitmap);
                iv.setImageBitmap(fitBitmap);
                iv.setVisibility(View.VISIBLE);
                myViewGroup.removeAllViews();
                myViewGroup.init();
                stopProgressBar();
            }
        });

    }

    private void startProgressBar() {
        loading.setVisibility(View.VISIBLE);
    }

    void stopProgressBar() {
        loading.setVisibility(View.GONE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            //打开相机后返回
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    /**
                     * 这种方法是通过内存卡的路径进行读取图片，所以的到的图片是拍摄的原图
                     */
                    displayImage(outputImagepath.getAbsolutePath());
                    Log.i("tag", "拍照图片路径>>>>" + outputImagepath);
                }
                break;
            //打开相册后返回
            case SELECT_PHOTO:
                if (resultCode == RESULT_OK) {
                    //判断手机系统版本号
                    if (Build.VERSION.SDK_INT > 19) {
                        //4.4及以上系统使用这个方法处理图片
                        handleImgeOnKitKat(data);
                    } else {
                        handleImageBeforeKitKat(data);
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                //判断是否有权限
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();//打开相册
//                    take_photo();//打开相机
                } else {
                    Toast.makeText(this, "你需要许可", Toast.LENGTH_LONG).show();
                }
                break;
            case 12:
                //判断是否有权限
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
                    Contants.IMEI = TelephonyMgr.getDeviceId();
                } else {
                    Toast.makeText(this, "你需要许可", Toast.LENGTH_LONG).show();
                    finish();
                }
                break;
            default:
                break;
        }
    }

    void requestImei() {
        //Android6.0需要动态获取权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
//            toast("需要动态获取权限");
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE}, 12);
        } else {
//            toast("不需要动态获取权限");
            TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
            Contants.IMEI = TelephonyMgr.getDeviceId();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (orc_bitmap != null) {
//            orc_bitmap.recycle();
//        } else {
//            orc_bitmap = null;
//        }
    }

    @Override
    public void gameover(final String time) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, "用时" + time + "秒", Toast.LENGTH_SHORT).show();
            }
        }, 200);
        checkData(time);
    }

    private void checkData(final String time) {
        final int dura = Integer.valueOf(time);
        /**获取实例*/
        final GetRequest_InterFace request = RetrofitManager.getInstance().createReq(GetRequest_InterFace.class);
        Call<RankBean> requestCall = request.getCall("1");
        switch (gameTag) {
            case 3:
                requestCall = request.getCall("1");
                break;
            case 4:
                requestCall = request.getCall("2");
                break;
            case 5:
                requestCall = request.getCall("3");
                break;
        }
        requestCall.enqueue(new Callback<RankBean>() {
            @Override
            public void onResponse(Call<RankBean> call, Response<RankBean> response) {
                ranklistBeans.clear();
                List<RankBean.RanklistBean> ranklist = response.body().ranklist;
                Map<String, String> fields = new HashMap<>();
                fields.put("token", Contants.IMEI);
                fields.put("time", dura + "");
                Log.d(">>>>", "huode json" + ranklist);
                if (ranklist == null) {
                    needUpdate(fields);
                    return;
                }
                ranklistBeans.addAll(ranklist);
                boolean needUpdate = false;
                boolean contain = false;
                String name = "";
                boolean needAdd = false;
                for (RankBean.RanklistBean bean : ranklistBeans) {
                    if (Contants.IMEI.equals(bean.token)) {
                        contain = true;
                        name = bean.name;
                        needUpdate = dura < bean.time;
                    }
                    needAdd = dura < bean.time;
                }
                if (needUpdate) {
                    fields.put("name", name);
                    Toast.makeText(MainActivity.this, "已创造新纪录!", Toast.LENGTH_SHORT).show();
                    needUpdate(fields);
                } else if (needAdd) {
                    // 如果不包含 且需要添加
                    showDialog(fields);
                } else if (!contain && ranklistBeans.size() < 10) {
                    // 如果不包含 记录数小于十条 则添加
                    showDialog(fields);
                }
            }

            @Override
            public void onFailure(Call<RankBean> call, Throwable t) {
            }
        });

    }

    // 显示对话框
    public void showDialog(final Map<String, String> fields) {
        // LayoutInflater是用来找layout文件夹下的xml布局文件，并且实例化
        LayoutInflater factory = LayoutInflater.from(this);
        // 把布局文件中的控件定义在View中
        final View textEntryView = factory.inflate(R.layout.my_dialog, null);

        // 将自定义xml文件中的控件显示在对话框中
        new AlertDialog.Builder(this)
                // 对话框的标题
                .setTitle("请留尊姓大名")
                // 设定显示的View
                .setView(textEntryView)
                // 对话框中的“完成”按钮的点击事件
                .setPositiveButton("完成", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // 获取用户输入的验证码
                        // 注意：textEntryView.findViewById很重要，因为上面factory.inflate(R.layout.activity_mobile_authentication_check_code,
                        // null)将页面布局赋值给了textEntryView了
                        final EditText et_name = (EditText) textEntryView.findViewById(R.id.et_name);
                        // 将页面输入框中获得的数据转为字符串
                        String checkCode = et_name.getText().toString().trim();
                        fields.put("name", checkCode);
                        // 现在为止已经获得了字符型的用户名和密码了，接下来就是根据自己的需求来编写代码了
                        needUpdate(fields);

                    }
                })
                // 对话框的“退出”单击事件
                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        //不做操作，关闭对话框
                    }
                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(false)
                // 对话框的创建、显示
                .create().show();
    }

    private void needUpdate(Map<String, String> fields) {
        Log.d(">>>>", "ksishi gengxin");
        final PostRequest_Interface request = RetrofitManager.getInstance().createReq(PostRequest_Interface.class);
        Call<RankBean> requestCall = request.getCall("1", fields);
        switch (gameTag) {
            case 3:
                requestCall = request.getCall("1", fields);
                break;
            case 4:
                requestCall = request.getCall("2", fields);
                break;
            case 5:
                requestCall = request.getCall("3", fields);
                break;
        }
        requestCall.enqueue(new Callback<RankBean>() {
            @Override
            public void onResponse(Call<RankBean> call, Response<RankBean> response) {
            }

            @Override
            public void onFailure(Call<RankBean> call, Throwable t) {
            }
        });
    }


    //改变拍完照后图片方向不正的问题
   /* private void ImgUpdateDirection(String filepath) {
        int digree = 0;//图片旋转的角度
        //根据图片的URI获取图片的绝对路径
        Log.i("tag", ">>>>>>>>>>>>>开始");
        //String filepath = ImgUriDoString.getRealFilePath(getApplicationContext(), uri);
        Log.i("tag", "》》》》》》》》》》》》》》》" + filepath);
        //根据图片的filepath获取到一个ExifInterface的对象
        ExifInterface exif = null;
        try {
            exif = new ExifInterface(filepath);
            Log.i("tag", "exif》》》》》》》》》》》》》》》" + exif);
            if (exif != null) {

                // 读取图片中相机方向信息
                int ori = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);

                // 计算旋转角度
                switch (ori) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        digree = 90;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        digree = 180;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        digree = 270;
                        break;
                    default:
                        digree = 0;
                        break;

                }

            }
            //如果图片不为0
            if (digree != 0) {
                // 旋转图片
                Matrix m = new Matrix();
                m.postRotate(digree);
                orc_bitmap = Bitmap.createBitmap(orc_bitmap, 0, 0, orc_bitmap.getWidth(),
                        orc_bitmap.getHeight(), m, true);
            }
            if (orc_bitmap != null) {
                imageView.setImageBitmap(orc_bitmap);
            }
        } catch (IOException e) {
            e.printStackTrace();
            exif = null;
        }
    }*/

}
